package mark_2.io_1;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class ImageDownloader {
    public void download(String strUrl, String targetFiePath) throws IOException {
        URL url = new URL(strUrl);
        URLConnection connection = url.openConnection();

        try (InputStream inputStream = connection.getInputStream()) {
            File outFile = new File(targetFiePath);
            File dirs = outFile.getParentFile();
            dirs.mkdirs();

            try (FileOutputStream outputStream = new FileOutputStream(targetFiePath)) {
                int count;
                byte[] buffer = new byte[1024 * 4];
                while((count = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, count);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
